package com.isyscore.controller;

import com.isyscore.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
 * @Author: liuxq@isyscore.com
 * @Date: 2021-04-21 15:37:41
 * @Description: 覆盖默认请求
 */
@RestController
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public ResponseVo<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return tokenInfo(tokenEndpoint.getAccessToken(principal, parameters).getBody());

    }

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ResponseVo<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return tokenInfo(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }

    private ResponseVo<OAuth2AccessToken> tokenInfo(OAuth2AccessToken auth2AccessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) auth2AccessToken;
        token.getAdditionalInformation().remove("jti");
        return ResponseVo.success(token);
    }

}
